<script lang="ts" setup>
import {onBeforeUnmount, onMounted, ref, shallowRef} from 'vue';
import request from "../../service/request";
import {message} from 'ant-design-vue';
import {Tool} from "@/util/tool";
import {useRoute} from "vue-router";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';

const docs: any = ref();//所有文档
const tree: any = ref();//表格树形结构
const doc: any = ref({});//当前文档
const treeDataValue: any = ref();//树选择绑定的树形结构
const loading = ref(false);//表格数据加载等待
let ids: any[] = [];
const route = useRoute();
const mode = ref('default');
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref();
const toolbarConfig = {};
const drawerVisible = ref(false);
const html = ref();

const editorConfig:any={MENU_CONF:{}}
editorConfig.placeholder = "请在这里输入内容..."
type InsertFnType = (url: string, alt: string, href: string) => void

editorConfig.MENU_CONF['uploadImage']={
  server: 'http://127.0.0.1:8888/doc/upload-img', // 上传图片地址

  timeout: 5 * 1000, // 5s

  fieldName: 'file',
  headers: {Accept: 'text/x-json'},

  maxFileSize: 10 * 1024 * 1024, // 10M
  customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
    // res 即服务端的返回结果

    // 从 res 中找到 url alt href ，然后插入图片
    insertFn("data:image/*;base64,"+res.data[0],"失败",res.data[0])
  },

  onBeforeUpload(files: any) {
    console.log('onBeforeUpload', files)

    return files // 返回哪些文件可以上传
    // return false 会阻止上传
  },
  onProgress(progress: any) {
    console.log('onProgress', progress)
  },
  onSuccess(file: any, res: any) {
    console.log('Success')
  },
  onFailed(file: any, res: { message: any; }) {
    console.log("Failed")
  },
  onError(file: any, err: { message: any; }, res: any) {
    console.error('Error')
  },
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
});
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
};

/**
 * 表格绑定的columns
 */
const columns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: 'Action',
    key: 'action',
  }
];
/**
 * 数据查询
 **/
const handleQuery = () => {
  loading.value = true;
  request.get("/doc/all/" + route.query.ebookId).then((res) => {
    loading.value = false;
    docs.value = res.data
    tree.value = [];
    tree.value = Tool.array2Tree(docs.value, 0);

    treeDataValue.value = Tool.copy(tree.value)
    setDisable(treeDataValue.value, doc.value.id)
    treeDataValue.value.unshift({id: 0, name: '无'})
  })
};
/**
 * 内容查询
 **/
const handleQueryContent = () => {
  request.get("/doc/findContent/" + doc.value.id).then((res) => {
    const editor = editorRef.value
    editor.setHtml(res.data)
  })
};
/**
 * 编辑文档
 * @param record
 */
const edit = (record: any) => {
  doc.value = Tool.copy(record)
  handleQueryContent()

  treeDataValue.value = Tool.copy(tree.value)
  setDisable(treeDataValue.value, record.id)
  treeDataValue.value.unshift({id: 0, name: '无'})
};
/**
 * 添加文档
 */
const add = () => {
  doc.value = {}
  const editor = editorRef.value
  editor.setHtml('')
  treeDataValue.value = Tool.copy(tree.value)
  treeDataValue.value.unshift({id: 0, name: '无'})
};
/**
 * 删除文档
 * @param id
 */
const del = (id: number) => {
  ids=[]
  getDeleteIds(tree.value, id);
  request.delete("/doc/delete/" + ids.join(",")).then((res) => {
    const data = res.data;
    if (data.success) {
      handleQuery()
    }
  })
};
/**
 * 由id转化名称
 * @param cid
 */
const getDocName = (cid: number) => {
  let result = "无";
  docs.value.forEach((item: any) => {
    if (item.id == cid) {
      result = item.name
    }
  })
  return result;
};
const handlePreviewContent = () => {
  const editor = editorRef.value
  html.value = editor.getHtml();
  drawerVisible.value = true;
};
const onDrawerClose = () => {
  drawerVisible.value = false;
};
/**
 * 将某节点及其子孙节点全部置为disabled
 */
const setDisable = (treeDataValue: any, id: any) => {
  // 遍历数组，即遍历某一层节点
  for (let i = 0; i < treeDataValue.length; i++) {
    const node = treeDataValue[i]
    if (node.id === id) {
      // 如果当前节点就是目标节点
      // 将目标节点设置为disabled
      node.disabled = true;

      // 遍历所有子节点，将所有子节点全部都加上disabled
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        for (let j = 0; j < children.length; j++) {
          setDisable(children, children[j].id)
        }
      }
    } else {
      // 如果当前节点不是目标节点，则到其子节点再找找看。
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        setDisable(children, id);
      }
    }
  }
};
/**
 * 查找整根树枝
 */
const getDeleteIds = (treeSelectData: any, id: any) => {
  // 遍历数组，即遍历某一层节点
  for (let i = 0; i < treeSelectData.length; i++) {
    const node = treeSelectData[i];
    if (node.id === id) {
      // 如果当前节点就是目标节点
      // 将目标ID放入结果集ids
      ids.push(id);

      // 遍历所有子节点
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        for (let j = 0; j < children.length; j++) {
          getDeleteIds(children, children[j].id)
        }
      }
    } else {
      // 如果当前节点不是目标节点，则到其子节点再找找看。
      const children = node.children;
      if (Tool.isNotEmpty(children)) {
        getDeleteIds(children, id);
      }
    }
  }
};
/**
 * 保存事件
 */
const handleSave = () => {
  doc.value.ebookId=route.query.ebookId
  const editor = editorRef.value
  doc.value.content = editor.getHtml()
  request.post("/doc/save", doc.value
  ).then((res) => {
    const data = res.data;
    if (data.success) {
      handleQuery()
      message.success("保存成功")
    } else {
      message.error(data.message)
    }
  })
};
/**
 * 初始加载
 */
onMounted(() => {
  handleQuery();
});

</script>

<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form layout="inline">
            <a-form-item>
              <a-button type="primary" @click="add()">
                新增
              </a-button>
            </a-form-item>
          </a-form>
          <a-table
              v-if="tree?.length>0"
              :columns="columns"
              :data-source="tree"
              :row-key="record => record.id"
              :loading="loading"
              :pagination="false"
              :defaultExpandAllRows="true"
          >
            <template #bodyCell="{column,record }">
              <template v-if="column.key==='action'">
                <a-space size="small">
                  <a-button type="primary" @click="edit(record)">
                    编辑
                  </a-button>
                  <a-popconfirm
                      title="删除后不可恢复,确认删除吗?"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="del(record.id)"
                  >
                    <a-button type="danger">
                      删除
                    </a-button>
                  </a-popconfirm>

                </a-space>
              </template>
            </template>

          </a-table>
        </a-col>
        <a-col :span="16">
          <p>
            <a-form layout="inline">
              <a-form-item>
                <a-button type="primary" @click="handleSave()">
                  保存
                </a-button>
              </a-form-item>
            </a-form>
          </p>
          <a-form :model="doc" layout="vertical">
            <a-form-item>
              <a-input placeholder="name" v-model:value="doc.name"/>
            </a-form-item>
            <a-form-item>
              <a-tree-select
                  v-model:value="doc.parent"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  placeholder="请选择父文档"
                  :field-names="{value: 'id',label: 'name',key: 'id'}"
                  :tree-data="treeDataValue"
                  :treeDefaultExpandAll="true"
              >
              </a-tree-select>
            </a-form-item>
            <a-form-item>
              <a-input placeholder="sort" v-model:value="doc.sort"/>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handlePreviewContent()">
                <EyeOutlined /> 内容预览
              </a-button>
            </a-form-item>
            <a-form-item>
              <div class="content">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    :mode="mode"
                />
                <Editor
                    style="height: 500px; overflow-y: hidden;"
                    v-model="valueHtml"
                    :defaultConfig="editorConfig"
                    :mode="mode"
                    @onCreated="handleCreated"
                />
              </div>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-drawer width="900" placement="right" :closable="false" :visible="drawerVisible" @close="onDrawerClose">
        <div class="wangeditor" v-html="html"></div>
      </a-drawer>
    </a-layout-content>
  </a-layout>
</template>

<style lang="less" scoped>

.wangeditor :deep(p, li) {
  white-space: pre-wrap; /* 保留空格 */
  color: slateblue;
}

.wangeditor :deep(blockquote) {
  border-left: 8px solid #d0e5f2;
  padding: 10px 10px;
  margin: 10px 0;
  background-color: #f1f1f1;
}

.wangeditor :deep(code) {
  font-family: monospace;
  background-color: #eee;
  padding: 3px;
  border-radius: 3px;
}

.wangeditor :deep(pre > code) {
  display: block;
  padding: 10px;
}

.wangeditor :deep(table) {
  border-collapse: collapse;
}

.wangeditor :deep(td, th) {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}

.wangeditor :deep(th) {
  background-color: #f1f1f1;
}

.wangeditor :deep(ul, ol) {
  padding-left: 20px;
}

.wangeditor :deep(input[type="checkbox"]) {
  margin-right: 5px;
}

/* 图片自适应 */
.wangeditor :deep(img) {
  max-width: 100%;
  height: auto;
}

/* 视频自适应 */
.wangeditor :deep(iframe) {
  width: 100%;
  height: 400px;
}

</style>